package com.akxy.pt.tsdb.service.stress;

import com.akxy.pt.tsdb.domain.stress.StressDataInfo;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author Mengfly
 */
@Service
@Slf4j
public class StressTransformService {

    @Autowired
    private InfluxDBClient client;

    public void transform() throws ParseException {

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = simpleDateFormat.parse("2021-01-01 00:00:00");

        Random random = new Random();
        long cost = 0;
        int count = 0;
        while (parse.before(new Date())) {
            List<StressDataInfo> dataInfos = new ArrayList<>();
            WriteApiBlocking writeApiBlocking = client.getWriteApiBlocking();
            long l = System.currentTimeMillis();
            for (int i = 0; i < 1000; i++) {
                StressDataInfo dataInfo = new StressDataInfo();
                dataInfo.setMpId(String.valueOf(i + 1));
                dataInfo.setAreaId(String.valueOf(i % 200 + 1));
                dataInfo.setPValue(5 + random.nextDouble() * 5);
                dataInfo.setDayInc(random.nextDouble() * 2);
                dataInfo.setHourInc(random.nextDouble());
                dataInfo.setAllIncRate(100 * random.nextDouble());
                dataInfo.setTime(Instant.ofEpochMilli(parse.getTime()));
                dataInfos.add(dataInfo);
            }
            count++;
            cost += (System.currentTimeMillis() - l);
            writeApiBlocking.writeMeasurements("pt", "anke", WritePrecision.MS, dataInfos);
            log.info("数据写入到：{}, 平均耗时：{}", simpleDateFormat.format(parse), cost * 1. / count);
            // 一分钟写入一次数据
            parse = new Date(parse.getTime() + 1000 * 60);
        }
        log.info("数据写入完成, 总耗时{}", cost);
    }

}
